﻿using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Red.Controls.Extensions;
using Red.Controls.Shell;
using Red.Controls.Utils;
using Red.Controls.ViewModels;

namespace Red.Toolkit.AnimationGraphEditor.Pages
{
    /// <summary>
    /// Interaction logic for AnimVariableList.xaml
    /// </summary>
    public partial class AnimVariableList : UserControl
    {
        #region C-tor

        public AnimVariableList()
        {
            InitializeComponent();
        }

        #endregion C-tor

        #region Private properties

        private DataItem DataItem => (DataItem)DataContext;

        #endregion Private properties

        #region Properties

        public static DependencyProperty VariableTypeProperty = DependencyProperty.Register( "VariableType", typeof( string ), typeof( AnimVariableList ) );
        public string VariableType
        {
            get { return ( string ) GetValue( VariableTypeProperty ); }
            set { SetValue( VariableTypeProperty, value ); }
        }

        #endregion Properties

        #region Event handlers

        private async void Add_Click( object sender, RoutedEventArgs e )
        {
            var variableName = TextInputDialog.Show( this, null, "Variable name", "Create new variable" );
            if ( string.IsNullOrEmpty( variableName ) )
                return;

            await DataItem.ExecuteAsync( "add", variableName );

            // TODO: this will be removed when variables on the engine side will automatically send _onChanged events
            await DataItem.RebuildAsync();
        }

        private async void Remove_Click( object sender, RoutedEventArgs e )
        {
            var variableName = TextInputDialog.Show( this, null, "Variable name", "Remove existing variable" );
            if ( string.IsNullOrEmpty( variableName ) )
                return;

            await DataItem.ExecuteAsync( "remove", variableName );

            // TODO: this will be removed when variables on the engine side will automatically send _onChanged events
            await DataItem.RebuildAsync();
        }

        private void DataCategory_DragStart( object sender, DragStartEventArgs e )
        {
            var container = Helpers.FindVisualAncestorOfType<ListBoxItem>( e.OriginalSource );
            DataItem item = container?.DataContext as DataItem;

            if ( item != null )
            {
                e.DraggedData = Task.FromResult<IDataObject>( new DataObject( VariableType, item.Title ) );
            }
            else
            {
                e.DraggedData = Task.FromResult<IDataObject>( null );
            }
        }

        #endregion Event handlers
    }
}
